<?php

App::uses('CustomDataModel', 'Base.Model');
App::uses('ModelTraverser', 'Base.Lib');
App::uses('ConfigurationKeys', 'ConfigurationKeys.Lib');

class RawFileTag extends CustomDataModel {

    public $actsAs = array(
        'Base.CommonValidation'
    );
    public $validate = array(
        'tag_id' => array(
            'foreignKey' => array(
                'rule' => array('foreignKey'),
            ),
            'isUniqueInContext' => array(
                'rule' => array('isUniqueInContext', 'raw_file_id'),
            ),
        ),
        'raw_file_id' => array(
            'foreignKey' => array(
                'rule' => array('foreignKey'),
            ),
            'isUniqueInContext' => array(
                'rule' => array('isUniqueInContext', 'tag_id'),
            ),
        ),
        'name' => array(
            'notempty' => array(
                'rule' => array('notempty'),
            ),
            'isUniqueInContext' => array(
                'rule' => array('isUniqueInContext', 'tag_id'),
            ),
        ),
    );
    public $belongsTo = array(
        'Tag',
        'RawFile',
    );

    protected function customData() {
        $RawFile = ClassRegistry::init('RawFile');

        $Tag = ClassRegistry::init('Tag');
        $tags = $Tag->find('all');

        $data = array();

        foreach ($tags as $tag) {
            $tagDirectoryIterator = new DirectoryIterator($Tag->absolutePath($tag));
            while ($tagDirectoryIterator->valid()) {
                if ($tagDirectoryIterator->isLink()) {
                    if (substr($tagDirectoryIterator->getLinkTarget(), 0, 1) == '/') {
                        $linkTargetAbsolutePath = $tagDirectoryIterator->getLinkTarget();
                    } else {
                        $linkTargetAbsolutePath = realpath($Tag->absolutePath($tag) . '/' . $tagDirectoryIterator->getLinkTarget());
                    }
                    $rawFile = $this->RawFile->findByAbsolutePath($linkTargetAbsolutePath);

                    if (!empty($rawFile)) {
                        $data[] = array(
                            'name' => $tagDirectoryIterator->getFilename(),
                            'tag_id' => $tag['Tag']['id'],
                            'raw_file_id' => $rawFile['RawFile']['id'],
                        );
                    }
                }
                $tagDirectoryIterator->next();
            }
        }

        return $data;
    }

    protected function customSave($oldData, $newData) {
        if (empty($oldData)) {
            $rawFile = $this->RawFile->findById($newData['raw_file_id']);
            $tag = $this->Tag->findById($newData['tag_id']);
            $target = $this->RawFile->getAbsolutePath($rawFile);
            $name = empty($newData['name']) ?
                    $rawFile['RawFile']['name'] :
                    $newData['name'];
            $link = $this->Tag->absolutePath($tag) . DIRECTORY_SEPARATOR . $name;
            $this->executeOperation(FileOperations::symLink($target, $link));
            $this->data[$this->alias]['name'] = $name;
        }
        else {
            throw new Exception("Update not supported.");
        }        
    }

    protected function customDelete($row) {
        $this->executeOperation(FileOperations::unlink($this->absolutePath(array($this->alias => $row))));
    }

    public function absolutePath($rawFileTag) {
        return $this->Tag->absolutePath(
                        ModelTraverser::value($this, $rawFileTag, $this->Tag->alias)
                )
                . DIRECTORY_SEPARATOR . $rawFileTag[$this->alias]['name'];
    }

}

?>
